import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { DatePipe } from '@angular/common';
import { ActivatedRoute } from '@angular/router';
import { CommonService } from '../../../../services-common/common.service';
import { StorageCommonService } from '../../xstorage-manage-services/storage-common.service';
import { StorageWarehousOrderService } from '../../xstorage-manage-services/storage-warehous-order.service';

@Component({
  selector: 'app-storage-warehous-editpt',
  templateUrl: './storage-warehous-editpt.component.html',
  styleUrls: ['./storage-warehous-editpt.component.scss'],
  providers: [DatePipe]
})
export class StorageWarehousEditptComponent implements OnInit {

  routeParams: any = {};
  detailsData: any = {}; // 编辑详情

  flexLabelWidth: string = '108px';
  formParams: any = {
    type: '', // 入库类型
    supId: '', // 供应商
    whPutId: '', // 入库仓库
    quality: '', // 入库品质
    arrivalTime: '', // 预计到货日期
    contractEnclosure: '', // 附件
    remark: '', // 备注
  };
  supplierOptions: any[] = []; // 供应商Options
  warehouseOptions: any[] = []; // 仓库Options
  warehousTypeOptions: any[] = []; // 入库类型

  associatedTableData: Array<any> = []; // 已选商品(入库明细)

  submitLoading = false;

  /**
   * Bom Modal
   * ----------------------------------------------------------------
   */
  isBomVisible = false;
  bomGoodsId: number | string = '';

  /**
   * 选择商品
   * ----------------------------------------------------------------
   */
  isGoodVisible = false;
  goodTableParams: any = {
    code: '', // 查询条件
    loading: false,
    tableData: [],
    page: 1,
    pageSize: 10,
    total: 0
  };

  /**
   * ----------------------------------------------------------------
   * Table Check
   * ----------------------------------------------------------------
   */
  checked = false;
  indeterminate = false;
  listOfCurrentPageData: readonly any[] = [];
  setOfCheckedId = new Set<number>();
  setOfCheckedArr: Array<any> = [];

  updateCheckedSet(id: number, checked: boolean): void {
    if (checked) {
      let checkedItem = this.listOfCurrentPageData.find(item => item.id === id);
      let setIds = this.setOfCheckedArr.map(m => m.whGoodsId);
      this.setOfCheckedId.add(id);

      if (!setIds.includes(id)) {
        // 注：push的 type为入库商品的type，与原商品列表的type区分、状态分别为(0 指定SN 1 SN管控 2 多库位 3 普通)
        this.setOfCheckedArr.push({
          ...checkedItem,
          whGoodsId: id,
          whGoodsState: checkedItem.state, // 商品状态
          whGoodsName: checkedItem.name, // 商品名称
          whGoodsCode: checkedItem.goodsCode, // 商品编号
          whGoodsTwoCode: checkedItem.code, // 商品69码
          type: checkedItem.snState === 0 ? 1 : 3 // 是否sn管控
        });
      }
    } else {
      let delCheckedIndex = this.setOfCheckedArr.findIndex(item => item.whGoodsId === id);
      this.setOfCheckedId.delete(id);

      this.setOfCheckedArr.splice(delCheckedIndex, 1);
    }
  }

  onItemChecked(id: number, checked: boolean): void {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus();
  }

  onAllChecked(value: boolean): void {
    this.listOfCurrentPageData.filter(tag => tag.state === 1).forEach(item => this.updateCheckedSet(item.id, value));
    this.refreshCheckedStatus();
  }

  onCurrentPageDataChange($event: readonly any[]): void {
    this.listOfCurrentPageData = $event;
    this.refreshCheckedStatus();
  }

  refreshCheckedStatus(): void {
    let listOfCurrentPageData = this.listOfCurrentPageData.filter(tag => tag.state === 1);
    this.checked = listOfCurrentPageData.every(item => this.setOfCheckedId.has(item.id));
    this.indeterminate = listOfCurrentPageData.some(item => this.setOfCheckedId.has(item.id)) && !this.checked;
  }

  constructor(
    private msg: NzMessageService,
    private datePipe: DatePipe,
    private activatedRoute: ActivatedRoute,
    private commonService: CommonService,
    private storageCommonService: StorageCommonService,
    private services: StorageWarehousOrderService
  ) {
    activatedRoute.queryParams.subscribe((res: any) => {
      this.routeParams = res || {};
    })
  }

  ngOnInit(): void {
    this.loadSupplierList();
    this.loadWarehouseList();
    this.loadPutTypeOptionData();

    if (this.routeParams.id) {
      this.loadDetailsData();
    }
  }

  async loadDetailsData() {
    let params = {
      id: this.routeParams.id
    }
    const msgId = this.msg.loading('数据加载中..', { nzDuration: 0 }).messageId;
    const {code, data, message}: any = await this.services.getWarehousingDetails(params);
    this.msg.remove(msgId);
    
    if (code === 0) {
      const { list, warehousing } = data || {};
      
      this.detailsData = warehousing || {};
      for (let key in this.formParams) {
        this.formParams[key] = !this.commonService.isEmpty(warehousing[key]) ? warehousing[key] : '';
      }

      this.formParams.type = String(warehousing.type) || '';
      this.formParams.supId = Number(warehousing.supId) || '';
      this.associatedTableData = list || [];
    } else {
      this.msg.error(message);
    }
  }

  // 入库类型
  async loadPutTypeOptionData() {
    const res: any = await this.commonService.getDictList('inbound_type');
    this.warehousTypeOptions = res || [];
  }

  // 查询供应商
  async loadSupplierList() {
    const res: any = await this.commonService.getSupplierList();
    // 状态为正常de
    this.supplierOptions = res.filter((item: any) => item.state === 1);
  }

  // 查询仓库
  async loadWarehouseList() {
    let params = {
      page: 1,
      pageSize: 9999
    }
    const {code, data, message}: any = await this.storageCommonService.getWarehouseList(params);
    if (code === 0) {
      this.warehouseOptions = data?.records.filter((item: any) => [1].includes(item.state));
    } else {
      this.msg.error(message);
    }
  }

  /**
   * 选择更多商品
   * ----------------------------------------------------------------
   */
  async showMoreGoodsModal() {
    await this.loadGoodTable();
    
    let arr = this.associatedTableData.map(m => m.whGoodsId);
    this.setOfCheckedId = new Set(arr);
    this.setOfCheckedArr = JSON.parse(JSON.stringify(this.associatedTableData));
    this.isGoodVisible = true;
  }

  /**
   * ----------------------------------------------------------------
   * 仓储商品 Modal
   * ----------------------------------------------------------------
   */
  async loadGoodTable() {
    let params = {
      exsistSN: 1,
      code: this.goodTableParams.code,
      page: this.goodTableParams.page,
      pageSize: this.goodTableParams.pageSize
    }
    this.goodTableParams.loading = true;
    const {code, data, message}: any = await this.storageCommonService.getWhlistData(params);
    this.goodTableParams.loading = false;
    
    if (code === 0) {
      this.goodTableParams.tableData = data.records || [];
      this.goodTableParams.total = data.total || 0;
    } else {
      this.msg.error(message);
    }
  }

  searchGoodsData() {
    this.goodTableParams.page = 1;
    this.loadGoodTable();
  }

  resetGoodsData() {
    this.goodTableParams.code = '';
    this.goodTableParams.page = 1;
    this.loadGoodTable();
  }

  // PageIndex Change
  onPageIndexChange(index: number) {
    this.goodTableParams.page = index;
    this.loadGoodTable();
  }

  // PageSize Change
  onPageSizeChange(sizeNum: number) {
    this.goodTableParams.page = 1;
    this.goodTableParams.pageSize = sizeNum;
    this.loadGoodTable();
  }

  // 关联已选
  relationSelected() {
    if (!this.setOfCheckedId.size) {
      this.msg.warning('请先选择所需关联项!');
      return
    }
    // return
    this.associatedTableData = JSON.parse(JSON.stringify(this.setOfCheckedArr));
    this.isGoodVisible = false;
  }

  /**
   * BOM Handle Modal
   * ----------------------------------------------------------------
   */
  showBomModal(item: any) {
    this.bomGoodsId = item.id;
    this.isBomVisible = true;
  }

  bomHandle(val: any) {
    let tmpIds = this.associatedTableData.map((m: any) => m.whGoodsId);
    let tmpTips: any[] = [];

    val.forEach((item: any) => {
      if (!tmpIds.includes(item.id)) {
        let obj = {
          ...item,
          whGoodsId: item.id,
          whGoodsState: item.state, // 商品状态
          whGoodsName: item.name || '', // 商品名称
          whGoodsCode: item.goodsCode || '', // 商品编号
          whGoodsTwoCode: item.code || '', // 商品69码
          type: item.snState === 0 ? 1 : 3 // 是否sn管控
        }
        this.associatedTableData = this.associatedTableData.concat([...obj]);
      } else {
        tmpTips.push(item.name);
      }
    })

    if (tmpTips.length) {
      this.msg.warning(`商品 ${tmpTips.join('、')} 已存在`);
    }
    this.isGoodVisible = false;
  }

  /**
   * other
   * ----------------------------------------------------------------
   */
  pageBack() {
    history.back();
  }

  // 入库数量 \ 单价合计
  calcSumTotal(key: string) {
    let sum = 0;
    sum = this.associatedTableData.reduce((total: number, item: any) => {
      return (total || 0) + (item[key] || 0);
    }, 0);

    return isNaN(sum) ? 0 : sum;
  }

  // 行小计
  calcProduct(num: number, price: number) {
    let pTotal = 0;
    pTotal = num * (price ? (Number(price)) : 0);

    return isNaN(pTotal) ? 0 : pTotal;
  }

  // 小计合计
  calcProductTotal() {
    let sum = 0;
    sum = this.associatedTableData.reduce((total: number, item: any) => {
      return (total || 0) + ((item.number || 0) * (item.price || 0));
    }, 0);

    return isNaN(sum) ? 0 : sum;
  }

  // 删除已关联项
  deleteGoodItem(item: any) {
    this.associatedTableData = this.associatedTableData.filter(d => d.id !== item.id);
  }

  // timechange
  timeChange(val: any) {
    this.formParams.arrivalTime = val ? this.datePipe.transform(val, 'yyyy-MM-dd') : '';
  }

  verifData() {
    let isNotFilled = this.associatedTableData.some(m => this.commonService.isEmpty(m.number));

    if (this.commonService.isEmpty(this.formParams.type)) {
      this.msg.warning('请选择入库类型');
      return false;
    } else if (this.commonService.isEmpty(this.formParams.whPutId)) {
      this.msg.warning('请选择入库仓库');
      return false;
    } else if (this.commonService.isEmpty(this.formParams.quality)) {
      this.msg.warning('请选择入库品质');
      return false;
    } else if (!this.associatedTableData.length) {
      this.msg.warning('请添加入库明细');
      return false;
    } else if (isNotFilled) {
      this.msg.warning('入库明细中预计入库数量存在未填写项');
      return false;
    } else {
      return true;
    }
  }

  /**
   * submit
   * ----------------------------------------------------------------
   */
  async submitData() {
    if (!this.verifData()) {
      return
    }

    let arrs = this.associatedTableData.map(m => {
      return {
        whGoodsId: m.whGoodsId, // 商品ID
        number: m.number, // 入库数量
        price: m.price, // 入库单价
        state: (this.routeParams.id && !this.commonService.isEmpty(m.lineState)) ? m.lineState : 0, // 状态 0正常(新增默认) 1已作废
        type: m.type,  // 商品列表type为分类 (注:编辑时使用返回type即可、新增时根据原商品列表中snState设置type，snState:0对应1、1对应3) // type: 0 指定SN 1SN管控 2多库位 3普通(新增默认)
        closeRemark: !this.commonService.isEmpty(m.closeRemark) ? m.closeRemark : '', // 关闭备注
        actualStorageNumber: !this.commonService.isEmpty(m.actualStorageNumber) ? m.actualStorageNumber : '', // 实际入库数量
        itemSns: !this.commonService.isEmpty(m.itemSns) ? m.itemSns : '', // 商品SN号列表
        libraryText: !this.commonService.isEmpty(m.libraryText) ? m.libraryText : '', // 库位信息
        libraryId: !this.commonService.isEmpty(m.libraryId) ? m.libraryId : '' // 库位id
      }
    })

    let params: any = {
      warehousing: {
        ...this.formParams
      },
      list: arrs
    }
    if (this.routeParams.id) {
      params.warehousing.id = this.routeParams.id;
    }
    // return
    this.submitLoading = true;
    const {code, message}: any = await this.services.editWarehousOrderData(params, this.routeParams.id ? 1 : 0);
    this.submitLoading = false;

    if (code === 0) {
      this.msg.success('操作成功');
      this.pageBack();
    } else {
      this.msg.error(message);
    }
  }
}
